/**
 * Created by JOKER on 2017/7/20.
 */
'use strict';
(function (window, angular, undefined) {
    app.service("ngTableService", ngTableService);
    ngTableService.$inject = ['$http', '$q', 'NgTableParams', '$rootScope'];// 注入依赖
    function ngTableService($http, $q, NgTableParams, $rootScope) {
        var services = {
            init: init,//初始化对象(前端分页)
            initGroup: initGroup,//初始化对象(前端分页)
            ajax: ajax, //后台分页
            addRow: addRow,//添加数据
            removeRow: removeRow,//移除数据
            addRowTable2Table: addRowTable2Table,//两个table间互相添加移除数据(前端分页使用)
            addMulRowTable2Table: addMulRowTable2Table,
            setData: setData,//设置数据
            getData: getData,
            reload: reload, //数据重载
            clean: clean,
            watchCheckBox: watchCheckBox,//全选选择框
            getChoiceData: getChoiceData
        };
        return services;

        function init(listData) {
            return new NgTableParams({}, {counts: [], dataset: listData==null ? [] : listData});
        }

        function initGroup(listData, groupSetting) {
            groupSetting = angular.extend(groupSetting, {});
            return new NgTableParams(groupSetting, {counts: [], dataset: listData});
        }

        function ajax(searchCriteria) {
            if (null != searchCriteria) {
                searchCriteria = angular.extend(searchCriteria, {pageRange: {size: 10, page: 0}});
            }
            return new NgTableParams({sorting: searchCriteria.orderBy}, {
                counts: [10, 20, 50],
                getData: function (params) {
                    searchCriteria.pageRange.page = params.page() - 1;
                    var sort = params.sorting();
                    searchCriteria.pageRange.orderBy = _.keys(sort)[0];
                    searchCriteria.pageRange.sortBy = _.values(sort)[0];
                    searchCriteria.pageRange.size = params.count();
                    return $http({
                        method: 'post',
                        url: searchCriteria.url,
                        data: searchCriteria,
                        cache: false
                    }).then(function successCallback(response) {
                        params.total(response.data.data.totalElements);
                        return response.data.data.content;
                    }, function errorCallback(response) {

                    });
                }
            });
        }

        function addRow(tableParams, row) {
            tableParams = tableParams || new NgTableParams({}, {counts: [], dataset: []});
            if (tableParams.settings().dataset == null || _.isUndefined(tableParams.settings().dataset)) {
                tableParams.data.unshift(row);
            } else {
                if (_.isArray(row)) {
                    tableParams.settings().dataset.push.apply(row);
                } else {
                    tableParams.settings().dataset.unshift(row);
                }
            }
            tableParams.page(1);
            tableParams.reload(function (data) {
                if (data.length === 0 && tableParams.total() > 0) {
                    tableParams.page(tableParams.page() - 1);
                    tableParams.reload();
                }
            });
        }

        function addRowTable2Table(tableParams1, tableParams2, row) {
            services.removeRow(tableParams1, row);
            services.addRow(tableParams2, row);
        }

        /**
         * 两个table之间数据交互
         * @param tableParams1
         * @param tableParams2
         * @param mulRow  多条记录
         */
        function addMulRowTable2Table(tableParams1, tableParams2, mulRow) {
            if (mulRow == null || mulRow.length == 0) return;
            _.forEach(mulRow, function (obj, index) {
                services.removeRow(tableParams1, obj);
                services.addRow(tableParams2, obj);
            });
        }

        /*function addRowTable2Table(tableParams1,tableParams2,addRow,removeRow){
         services.removeRow(tableParams1,removeRow);
         services.addRow(tableParams2,addRow);
         }*/

        function removeRow(tableParams, row) {
            _.remove(tableParams.settings().dataset, function (item) {
                return row === item;
            });
            //重新加载对象数据
            tableParams.reload().then(function (data) {
                if (data.length === 0 && tableParams.total() > 0) {
                    tableParams.page(tableParams.page() - 1);
                    tableParams.reload();
                }
            });
        }

        function setData(tableParams, data) {
            tableParams = tableParams || new NgTableParams({}, {counts: [], dataset: []});
            tableParams.settings({dataset: data});
            return tableParams;
        }

        function getData(tableParams) {
            return tableParams.settings().dataset;
        }

        function reload(tableParams) {
            tableParams.page(1);
            tableParams.reload(function (data) {
                if (data.length === 0 && tableParams.total() > 0) {
                    tableParams.page(tableParams.page() - 1);
                    tableParams.reload();
                }
            });
        }

        function clean(tableParams) {
            tableParams.settings().dataset = [];
            tableParams.reload().then(function (data) {
                if (data.length === 0 && tableParams.total() > 0) {
                    tableParams.page(tableParams.page() - 1);
                    tableParams.reload();
                }
            });
        }

        function watchCheckBox(checkboxes, resultList) {
            // watch for check all checkbox
            $rootScope.$watch(function () {
                return checkboxes.checked;
            }, function (newValue, oldValue) {
                if (newValue !== oldValue) {
                    angular.forEach(resultList, function (item) {
                        checkboxes.items[item.id] = newValue;
                    });
                }
            });
            // watch for data checkboxes
            $rootScope.$watch(function () {
                return checkboxes.items;
            }, function (newValue, oldValue) {
                if (newValue !== oldValue) {
                    var checked = 0, unchecked = 0,
                        total = resultList.length;
                    angular.forEach(resultList, function (item) {
                        checked += (checkboxes.items[item.id]) || 0;
                        unchecked += (!checkboxes.items[item.id]) || 0;
                    });
                    if ((unchecked == 0) || (checked == 0)) {
                        checkboxes.checked = (checked == total);
                    }
                    // grayed checkbox
                    angular.element(".select-all").prop("indeterminate", (checked != 0 && unchecked != 0));

                }
            }, true);
        }

        /**
         * @param filterData [{},{}]
         * @param checkItems: {'id':true}->{'1':true,'2':false}
         */
        function getChoiceData(filterData, checkItems) {
            var idArry = [];
            _.forEach(checkItems, function (value, key, obj) {
                if (value == true) {
                    idArry.push(key);
                }
            });

            return _.chain(filterData).filter(function (obj) {
                return _.includes(idArry, obj.id+"");
            }).value();
        }


    }
})(window, window.angular);